package middleware

import (
	"context"
	"net/http"

	"learning.com/edu/models"
)

type contextKey string

const userContextKey = contextKey("user")

/**
 * 将用户信息保存在 HTTP 请求的上下文中
 */
func (m *Middleware) ContextSetUser(r *http.Request, user *models.User) *http.Request {
	ctx := context.WithValue(r.Context(), userContextKey, user);
	return r.WithContext(ctx)
}

/**
 * 从 HTTP 请求的上下文中获取用户信息
 */
func (m *Middleware) ContextGetUser(r *http.Request) *models.User {
	user, ok := r.Context().Value(userContextKey).(*models.User)
	if !ok {
		panic("missing user value in request context")
	}
	return user
}